package com.hmall.user.interceptors;


import com.hmall.user.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String authorization = request.getHeader("authorization");
        if(StringUtils.isBlank(authorization)){
            log.warn("非法用户访问！请求路径：{}",request.getRequestURI());
            //没有用户信息，未登录 禁止
            response.setStatus(403);
           return false;
        }
        //转换用户id
        Long aLong = Long.valueOf(authorization);
        //存入ThreadLocal
        UserHolder.setUser(aLong);
        //放行
        return true;
    }
    //后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);

    }

    //最终拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //用完清理ThreadLocal
        UserHolder.removeUser();
    }
}
